package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author BaiZY on 2020/8/25.
 * @version 1.0
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;
    /**
     * 根据商品分类id，查询规格组的集合
     * @param cid
     * @return
     */
    @Override
    public List<SpecGroupDTO> queryGroupByCategoryId(Long cid) {
        List<SpecGroup> groupList = getSpecGroups(cid);
        return SpecGroupDTO.convertEntityList(groupList);
    }

    private List<SpecGroup> getSpecGroups(Long cid) {
        return query().eq("category_id", cid).list();
    }

    /**
     * 根据条件查询规格组及规格参数集合
     * @param cid
     * @return
     */
    @Override
    public List<SpecGroupDTO> queryGroupAndParamByCategoryId(Long cid) {
        List<SpecGroup> list = getSpecGroups(cid);
        List<SpecGroupDTO> groupDTOList = SpecGroupDTO.convertEntityList(list);
        if (CollectionUtils.isEmpty(list)){
            throw new LyException(404,"该分类下,规格参数组不存在!");
        }
        for (SpecGroupDTO specGroupDTO : groupDTOList) {
            List<SpecParamDTO> specParamDTOList = specParamService.queryParamsByCondition(cid, specGroupDTO.getId(), null);
            specGroupDTO.setParams(specParamDTOList);
        }
        return groupDTOList;
    }
}
